package com.cmict.data.infra.service.message.job;

import com.cmict.data.framework.quartz.core.scheduler.SchedulerManager;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ScheduledMessageServiceImpl implements ScheduledMessageService {

    private static final String ANNOUNCEMENT_GROUP = "announcement";

    private static final String ANNOUNCEMENT_jobHandlerName = "ScheduledNotifyJob";

    private static final Integer retryCount = 1;

    private static final Integer retryInterval = 1000;

    @Resource
    private SchedulerManager schedulerManager;

    @Override
    public Boolean addJob(Long id, LocalDateTime startTime) {
        try {
            schedulerManager.addOnlyOneJob(id, ANNOUNCEMENT_GROUP, ANNOUNCEMENT_jobHandlerName, String.valueOf(id), startTime, retryCount, retryInterval);
        } catch (SchedulerException e) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean updateJob(Long id, LocalDateTime startTime) {
        try {
            schedulerManager.updateJob(id, ANNOUNCEMENT_GROUP, ANNOUNCEMENT_jobHandlerName, String.valueOf(id), startTime, retryCount, retryInterval);
        } catch (SchedulerException e) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean deleteJob(Long id) {
        try {
            schedulerManager.deleteJob(id, ANNOUNCEMENT_GROUP);
        } catch (SchedulerException e) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean checkExists(Long id) {
        try {
            schedulerManager.checkExists(id, ANNOUNCEMENT_GROUP);
        } catch (SchedulerException e) {
            return false;
        }
        return true;
    }

    @Override
    public JobDetail getJob(Long id) {
        try {
            return schedulerManager.getJob(new JobKey(String.valueOf(id), ANNOUNCEMENT_GROUP));
        } catch (SchedulerException e) {
            return null;
        }
    }

    @Override
    public List<? extends Trigger> getTriggersOfJob(Long id) {
        try {
            return schedulerManager.getTriggersOfJob(new JobKey(String.valueOf(id), ANNOUNCEMENT_GROUP));
        } catch (SchedulerException e) {
            return null;
        }
    }

    @Override
    public void triggerJob(Integer id) {
        try {
            schedulerManager.triggerJob(new JobKey(String.valueOf(id), ANNOUNCEMENT_GROUP));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


}
